package com.wnhz.work.yz.fragment.shoppingcard;


import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.google.gson.Gson;
import com.wnhz.work.yz.MainActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.activity.ProjectOrderActivity;
import com.wnhz.work.yz.activity.ReservedActivity;
import com.wnhz.work.yz.adapter.ProjectShopAdapter;
import com.wnhz.work.yz.bean.FirstUpdataBean;
import com.wnhz.work.yz.bean.ProjectBean;
import com.wnhz.work.yz.bean.ProjectChild1;
import com.wnhz.work.yz.bean.ProjectChild2;
import com.wnhz.work.yz.bean.YusuanOrderBean;
import com.wnhz.work.yz.dialog.SimpleDialog;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class ProjectFragment extends Fragment implements View.OnClickListener {
    private View view;
    private SwipeMenuListView my_listView;
    private ProjectShopAdapter mAdapter;
    private List<ProjectChild1> dataList = new ArrayList<>();
    private List<ProjectChild2> config = new ArrayList<>();
    private ProjectBean bean;
    private MainActivity activity;
    private ImageView iv_all_choose;

    private TextView tv_all_price;
    private RelativeLayout rl_bottom;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        activity = (MainActivity) getActivity();
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED);
        view = inflater.inflate(R.layout.fragment_project, null);
        initView();
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroyView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void post(FirstUpdataBean f) {
        dataList.get(f.getPosition()).setNums(f.getNum() + "");
        isAllSelect();
    }


    private void initView() {
        my_listView = (SwipeMenuListView) view.findViewById(R.id.my_listView);
        my_listView.setFlag(true);
        iv_all_choose = (ImageView) view.findViewById(R.id.iv_all_choose);
        view.findViewById(R.id.tv_go_order).setOnClickListener(this);
        view.findViewById(R.id.rl_all_choose).setOnClickListener(this);
        tv_all_price = (TextView) view.findViewById(R.id.tv_all_price);
        view.findViewById(R.id.qx).setOnClickListener(this);
        rl_bottom = (RelativeLayout) view.findViewById(R.id.rl_bottom);
        upload();
    }

    private static final String TAG = "ProjectFragment";

    public void upload() {
        activity.showDialog();
        if (MyApplication.getInstance().getUserBean() == null) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        XUtil.Post(Url.PACKAGE_PACKAGECARTLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess:PACKAGE= " + result);
                dataList.clear();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String re = jsonObject.optString("result");
                    if (re.equals("1")) {
                        bean = new ProjectBean();
                        Gson gson = new Gson();
                        bean = gson.fromJson(jsonObject.optString("info"), ProjectBean.class);
                        config = bean.getConfig();
                        dataList = bean.getData();
                        if (dataList.size() == 0) {
                            rl_bottom.setVisibility(View.GONE);
                        } else {
                            rl_bottom.setVisibility(View.VISIBLE);
                        }

//                        Log.e("-=商品的价格===tv_price==", "" + dataList.get(1).getPackage_money());
                        mAdapter = new ProjectShopAdapter(getActivity(), ProjectFragment.this, dataList);
                        my_listView.setAdapter(mAdapter);
                        //   isAllSelect();

                        SwipeMenuCreator creater = new SwipeMenuCreator() {
                            @Override
                            public void create(SwipeMenu menu) {


                                //同理create删除item
                                SwipeMenuItem deleteItem = new SwipeMenuItem(getContext());
                                // set item background
                                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, 0x3F, 0x25)));
                                // set item width
                                deleteItem.setWidth(dp2px(90));
                                // set item title
                                deleteItem.setTitle("删除");
                                // set item title fontsize
                                deleteItem.setTitleSize(18);
                                // set item title font color
                                deleteItem.setTitleColor(Color.WHITE);
                                // set a icon
                                //  deleteItem.setIcon(R.mipmap.ic_delete);
                                // add to menu
                                menu.addMenuItem(deleteItem);
                            }
                        };
                        my_listView.setMenuCreator(creater);
                        my_listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
                            @Override
                            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                                switch (index) {

                                    case 0:
                                        //删除的逻辑
                                        activity.showDialogv7("确定删除该件商品吗？", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                updelete(position);
                                                mAdapter.notifyDataSetChanged();
                                            }
                                        });
                                        break;

                                    default:
                                        break;
                                }
                                return false;
                            }
                        });
                    } else {
                        rl_bottom.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                super.onFinished();
                activity.closeDialog();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
                Log.e("-----", "失败");
            }
        });
    }


    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, activity.getResources().getDisplayMetrics());
    }

    private void updelete(int position) {
        activity.showDialog();
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("cartId", dataList.get(position).getCart_id());
        XUtil.Post(Url.CART_DELCART, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i(TAG, "onSuccess:CART_DELCART=  " + result);
                try {

                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        activity.MyToast(info);
                        upload();
                    } else {
                        activity.MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                activity.closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                activity.closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private boolean isAllSelect = false;
    private int index = 0;
    private String selectName = "";
    private List<ProjectChild1> selectList = new ArrayList<>();

    @Override
    public void onClick(View v) {
        Intent intent;
        int num;
        int position;
        switch (v.getId()) {
            //选择
            case R.id.rl_choose:
                position = (int) v.getTag();
                List<ProjectChild1> selectList2 = new ArrayList<>();
                selectList2.clear();
                for (int i = 0; i < dataList.size(); i++) {
                    if (dataList.get(i).isSelect()) {
                        selectList2.add(dataList.get(i));
                    }
                }
                if (selectList2.size() == 1) {
                    selectList.add(selectList2.get(0));
                    selectName = selectList.get(0).getPackage_cate();
                }
                if (selectList2.size() == 0) {
                    selectName = "";
                    selectList.clear();
                }
                ProjectChild1 bean1 = dataList.get(position);
                if (!selectName.equals("")) {
                    if (!bean1.getPackage_cate().equals(selectName)) {
                        activity.MyToast("请选择相同类型商品");
                        return;
                    }
                }

                bean1.setSelect(!bean1.isSelect());
                ImageView se = (ImageView) v.getTag(R.id.add111);
                if (dataList.get(position).isSelect()) {
                    se.setImageResource(R.mipmap.ic_choose_li);
                } else {
                    se.setImageResource(R.mipmap.ic_choose_nor);
                }
                selectList2.clear();
                for (int i = 0; i < dataList.size(); i++) {
                    if (dataList.get(i).isSelect()) {
                        selectList2.add(dataList.get(i));
                    }
                }
                if (selectList2.size() == 1) {
                    selectList.add(selectList2.get(0));
                    selectName = selectList.get(0).getPackage_cate();
                }
                if (selectList2.size() == 0) {
                    selectName = "";
                    selectList.clear();
                }

                isAllSelect();
                break;

            case R.id.rl_all_choose:
            case R.id.qx:
                if (dataList.size() < 1) {
                    iv_all_choose.setImageResource(R.mipmap.ic_choose_nor);
                    activity.MyToast("请先添加项目");
                    return;
                }
                isAllSelect = !isAllSelect;
                if (isAllSelect) {
                    iv_all_choose.setImageResource(R.mipmap.ic_choose_li);
                } else {
                    iv_all_choose.setImageResource(R.mipmap.ic_choose_nor);
                }
                if (selectList.size() == 0) {
                    selectName = dataList.get(0).getPackage_cate();

                }
                if (isAllSelect) {
                    for (int i = 0; i < dataList.size(); i++) {
                        if (!dataList.get(i).getPackage_cate().equals(selectName)) {
                            continue;
                        } else {
                            dataList.get(i).setSelect(isAllSelect);
                        }
                        try {
                            ImageView tv = (ImageView) my_listView.getChildAt(i).findViewById(R.id.iv_choose);
                            if (tv != null) {
                                if (!dataList.get(i).getPackage_cate().equals(selectName)) {
                                    continue;
                                } else {
                                    tv.setImageResource(isAllSelect ? R.mipmap.ic_choose_li : R.mipmap.ic_choose_nor);
                                }
                            }
                        } catch (Exception e) {
                        }

                    }
                } else {
                    selectList.clear();
                    for (int i = 0; i < dataList.size(); i++) {
                        dataList.get(i).setSelect(isAllSelect);
                        try {
                            ImageView tv = (ImageView) my_listView.getChildAt(i).findViewById(R.id.iv_choose);
                            if (tv != null) {
                                tv.setImageResource(isAllSelect ? R.mipmap.ic_choose_li : R.mipmap.ic_choose_nor);
                            }
                        } catch (Exception e) {
                        }

                    }

                }
                isAllSelect();

                break;

            //项目下单
            case R.id.tv_go_order:
                if (selectName.equals("")) {
                    Toast.makeText(getContext(), "请选择购买商品!", Toast.LENGTH_SHORT).show();

                } else if (selectName.equals("整体浴室") || selectName.contains("厨房")) {
                    index = 0;
                    activity.showDialog();
                    new Thread() {
                        @Override
                        public void run() {
                            for (int i = 0; i < dataList.size(); i++) {
                                changeNum(Integer.parseInt(dataList.get(i).getNums()), dataList.get(i).getCart_id(), true);
                            }
                            super.run();
                        }
                    }.start();
                } else if (selectName.equals("工业化内装")) {
                    final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                    View view = View.inflate(activity, R.layout.dialog_goto_buy, null);
                    TextView goto_buy_pay = (TextView) view.findViewById(R.id.goto_buy_pay);
                    TextView goto_reserved = (TextView) view.findViewById(R.id.goto_reserved);

                    builder.setView(view);
                    final AlertDialog show = builder.show();
                    Window dialogWindow = show.getWindow();
                    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                    dialogWindow.setGravity(Gravity.CENTER);
                    dialogWindow.setAttributes(lp);
                    goto_buy_pay.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            index = 0;
                            activity.showDialog();
                            new Thread() {
                                @Override
                                public void run() {
                                    for (int i = 0; i < dataList.size(); i++) {
                                        changeNum(Integer.parseInt(dataList.get(i).getNums()), dataList.get(i).getCart_id(), true);
                                    }
                                    super.run();
                                }
                            }.start();
                            show.dismiss();
                        }
                    });
                    goto_reserved.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            index = 0;
                            activity.showDialog();
                            new Thread() {
                                @Override
                                public void run() {
                                    for (int i = 0; i < dataList.size(); i++) {
                                        changeNum(Integer.parseInt(dataList.get(i).getNums()), dataList.get(i).getCart_id(), false);
                                    }
                                    super.run();
                                }
                            }.start();
                            show.dismiss();
                        }
                    });

                }
                break;
            case R.id.reduce:
                position = (int) v.getTag();
                num = Integer.parseInt(dataList.get(position).getNums());
                if (num > 1) {
                    num--;
                    dataList.get(position).setNums(num + "");
                    TextView text = (TextView) v.getTag(R.id.add111);
                    text.setText(dataList.get(position).getNums());
                } else {
                    Toast.makeText(getContext(), "再减就没了!", Toast.LENGTH_SHORT).show();
                }
                isAllSelect();
                break;
            case R.id.iv_add:
                position = (int) v.getTag();
                num = Integer.parseInt(dataList.get(position).getNums());
                num++;

                TextView text = (TextView) v.getTag(R.id.add111);
                dataList.get(position).setNums(num + "");
                text.setText(dataList.get(position).getNums());
                isAllSelect();
                break;

            default:
                break;
        }
    }

    @Override
    public void onResume() {
        upload();
        isAllSelect();
        super.onResume();
    }

    private void isAllSelect() {
        double nums = 0;
        double pricce = 0;
        double all = 0;
        isAllSelect = true;
        double radio = 1;
        for (int i = 0; i < dataList.size(); i++) {
            if (dataList.get(i).isSelect()) {
                nums = Integer.parseInt(dataList.get(i).getNums());
                pricce = Double.parseDouble(dataList.get(i).getPackage_money());
                double prices = nums * pricce * radio;
                all += prices;
            } else {
                if (!dataList.get(i).getPackage_cate().equals(selectName))
                    continue;
                isAllSelect = false;
            }
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        tv_all_price.setText(df.format(all));
        if (isAllSelect && dataList.size() != 0) {
            iv_all_choose.setImageResource(R.mipmap.ic_choose_li);
        } else {
            iv_all_choose.setImageResource(R.mipmap.ic_choose_nor);
        }
        if (selectName.equals("")) {
            isAllSelect = false;
            iv_all_choose.setImageResource(R.mipmap.ic_choose_nor);
        }
        if (mAdapter != null)
            mAdapter.notifyDataSetChanged();
    }


    private void changeNum(int num, String cartId, final boolean flag) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("cartId", cartId);
        map.put("nums", num);
        XUtil.Post(Url.CART_CARTCHANGENUM, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i(TAG, "onSuccess:CART_= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                index++;
            }

            @Override
            public void onFinished() {
                if (index == dataList.size()) {
                    activity.closeDialog();
                    Log.e("---", flag + "");
                    if (flag)
                        handler.sendEmptyMessage(1);
                    else
                        handler.sendEmptyMessage(2);
                }
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            upload();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ArrayList<ProjectChild1> dataList1;  dataList1 = new ArrayList<>();
            StringBuffer sb = new StringBuffer("");
            for (int i = 0; i < dataList.size(); i++) {
                if (dataList.get(i).isSelect()) {
                    dataList1.add(dataList.get(i));
                    sb.append("-" + dataList.get(i).getCart_id());
                    dataList.get(i).setSelect(false);
                }
            }
            switch (msg.what) {
                case 1:
                    if (dataList1.size() > 0) {
                        setStart(dataList1);

                    }
                    else {
                        activity.MyToast("请选择购买商品");
                    }
                    break;
                case 2:
                    if (sb.equals("")) {
                        activity.MyToast("请选择购买商品");
                        return;
                    }
                    Intent intent1 = new Intent(activity, ReservedActivity.class);
                    intent1.putExtra("cateId", sb.append("-").toString());
                    startActivity(intent1);
                    break;
            }
        }
    };

    private void setStart(final ArrayList<ProjectChild1> dataList1) {
        Map<String, Object> map = new HashMap<>();
        StringBuilder builder = new StringBuilder("-");
        for (int i = 0; i < dataList1.size(); i++) {
            builder.append(dataList1.get(i).getCart_id());
            builder.append("-");
        }
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("cartIds", builder);

        XUtil.Post(Url.ORDER_BUDGETBUYPAGE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("==项目下单 is_b==", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        YusuanOrderBean suna = gson.fromJson(result, YusuanOrderBean.class);

                        String allMoney = tv_all_price.getText().toString();

                        startActivityForResult(new Intent(getActivity(), ProjectOrderActivity.class).putExtra("dataList", dataList1)
                                .putExtra("bean", bean).putExtra("allMoney", allMoney).putExtra("bean99", suna), 1);

                    } else {
                        String info = jsonObject.optString("info");
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        Toast.makeText(getContext(), "" + info, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

}
